package com.xia.servlet;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.xia.entity.Student;
import com.xia.service.StudentService;
import com.xia.service.impl.StudentServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet(name = "StudentServlet",urlPatterns = "/student.action")
public class StudentServlet extends HttpServlet {
    StudentService studentService = new StudentServiceImpl();
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        response.setCharacterEncoding("UTF-8");
        String opr = (request.getParameter("opr") == null || "".equals(request.getParameter("opr")))
                ? "list" : request.getParameter("opr");
        switch (opr) {
            case "list":
                List<Student> list = studentService.selectAll();
                String jsonString = JSON.toJSONString(list, SerializerFeature.WriteNullStringAsEmpty);
                response.getWriter().print(jsonString);
                return;
            case "update":
                String updataid =request.getParameter("id");
                studentService.updateStudent(updataid);
                return;
            case "delete":
                String id = request.getParameter("id");
                studentService.deleteStudent(Integer.parseInt(id));
                request.getRequestDispatcher("/stuList.jsp").forward(request,response);
                return;

        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}
